package com.example.getfromservice.Category;

import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;


import android.util.Log;


public class DataHandler extends DefaultHandler {


	private List<Category> categoryList; 
	private String currElement = "";
	private boolean isProduct = false;
	public Context theContext;
	public String Qname = "";
	public String ID ="";
	public String NAME ="";
	
	
	
		public DataHandler(Context cont) {
		
			super();
		    categoryList = new ArrayList<Category>();
		    theContext = cont;
		    
		}
	
	
		//start of the XML document
		public void startDocument () { Log.i("DataHandler", "Start of XML document"); }

		//end of the XML document
		public void endDocument () { Log.i("DataHandler", "End of XML document"); }

		//opening element tag
		public void startElement (String uri, String name, String qName, Attributes atts)
		{
		    //handle the start of an element
			//find out if the element is a brand
			if(qName.equals("Category"))
			{
			    //set product tag to false
			    isProduct = false;
			    
			    Log.i("DataHandler",qName);
			}
			else if(qName.equals("categoryName"))
			{
				Qname = qName;	
			    isProduct = true;
			    
			    Log.i("CategoryName",qName);}
			
			else if(qName.equals("categoryId"))
			{
				Qname = qName;
			    isProduct = true;
			    
			    Log.i("CategoryID",qName);}
			
		}

		//closing element tag
		public void endElement (String uri, String name, String qName)
		{
		    //handle the end of an element
			if(qName.equals("Category"))
			{
			    currElement = "";
			}
		}

		//element content
		public void characters (char ch[], int start, int length)
		{
		    //process the element content
			//string to store the character content
			String currText = "";
			//loop through the character array
			for (int i=start; i<start+length; i++)
			{
			    switch (ch[i]) {
			    case '\\':
			        break;
			    case '"':
			        break;
			    case '\n':
			        break;
			    case '\r':
			        break;
			    case '\t':
			        break;
			    default:
			        currText += ch[i];
			        break;
			    }
			}
			//prepare for the next item
			if(isProduct && currText.length()>0)
			    {
				
					if(Qname.equals("categoryName") )
					{
							currElement = currText;
							
							Log.i("DataHandler",currElement);
							
							NAME = currElement;
						//	catobj.setName(currBrand);
					}
					
					if(Qname.equals("categoryId") )
					{
							currElement = currText;
							
							Log.i("DataHandler",currElement);
							
							ID = currElement;
						
					}
					
					if(ID != "" && NAME != "")
					{
						Category catobj = new Category();
						catobj.setID(Integer.parseInt(ID));
						catobj.setName(NAME);
						//catobj.setEdit(0);
						categoryList.add(catobj);
						ID ="";
						NAME ="";
						
					}
					
			    }
				
		}
		
	
		
		public ArrayList<Category> getData()
		{
		    //take care of SAX, input and parsing errors
		    try
		    {
		            //set the parsing driver
		        System.setProperty("org.xml.sax.driver","org.xmlpull.v1.sax2.Driver");
		            //create a parser
		        SAXParserFactory parseFactory = SAXParserFactory.newInstance();
		        SAXParser xmlParser = parseFactory.newSAXParser();
		            //get an XML reader
		        XMLReader xmlIn = xmlParser.getXMLReader();
		            //instruct the app to use this object as the handler
		        xmlIn.setContentHandler(this);
		            //provide the name and location of the XML file **ALTER THIS FOR YOUR FILE**
		        
		        
		        URL xmlURL = new URL("http://10.0.2.2:8020/categoryservice/category/0");
		            //open the connection and get an input stream
		        URLConnection xmlConn = xmlURL.openConnection();
		        InputStreamReader xmlStream = new InputStreamReader(xmlConn.getInputStream());
		            //build a buffered reader
		        BufferedReader xmlBuff = new BufferedReader(xmlStream);
		            //parse the data
		       
		        xmlIn.parse(new InputSource(xmlBuff));
		        
		    }
		    catch(SAXException se) { Log.e("AndroidTestsActivity", 
		            "SAX Error " + se.getMessage()); }
		    catch(IOException ie) { Log.e("AndroidTestsActivity", 
		            "Input Error " + ie.getMessage()); }
		    catch(Exception oe) { Log.e("AndroidTestsActivity", 
		            "Unspecified Error " + oe.getMessage()); }
		        //return the parsed product list
		    return (ArrayList<Category>) categoryList;
		}
		
		

}
